#include "book.h"
#include "ui_book.h"

#include <QUrl>
#include <QNetworkAccessManager>
#include<QNetworkReply>
#include<QNetworkRequest>
#include <QFileDialog>
Book::Book(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Book)
{
    ui->setupUi(this);
}

Book::~Book()
{
    delete ui;
}




void Book::on_searchbtn_clicked()
{

}


void Book::on_filepathbtn_clicked()
{
    QString filename;
    //选择下载的文件夹
    QUrl filepath=QFileDialog::getExistingDirectoryUrl(this,tr("open file"),QUrl(""),QFileDialog::ShowDirsOnly);
    ui->textEdit->append("选择下载文件的文件夹路径为："+filepath.toString());


}


void Book::on_updatebtn_clicked()
{

}


void Book::on_urlbtn_clicked()
{
    //下载文件的url
    //QUrl url();
    //下载设置好url的文件资源
    QUrl url=ui->urledit->text();
    ui->textEdit->append("下载文件资源的url为:"+url.toString());
    QString filename="test.jpg";
    downLoadAction(url);
}

///
/// \brief Book::downLoadAction 用于获取到url后下载的函数
/// \param url  文件下载的url
/// \param filepath  文件存储的父路径
/// \param filename  下载文件的文件名
///
void Book::downLoadAction(const QUrl url)
{

    //下载函数
    QNetworkAccessManager * manager=new QNetworkAccessManager(this);
    QNetworkRequest request;
    QNetworkReply *reply;

    //发送请求
    request.setUrl(url);
    reply=manager->get(request);

    connect(reply,&QNetworkReply::finished,this,[=](){

        if(reply->error()==QNetworkReply::NoError){
            qDebug()<<"请求发送成功"<<reply->readAll();
        }else {
            qDebug() << "请求失败: " << reply->errorString();
        }


        // 检测是否连接到服务器失败
        if (reply->error() == QNetworkReply::HostNotFoundError) {
            qDebug() << "Host not found. Could not connect to the server.";
        } else if (reply->error() == QNetworkReply::TimeoutError) {
            qDebug() << "Connection timed out.";
        } else {
            qDebug() << "Other error occurred.";
        }

        reply->deleteLater();
    });


}




